package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.config.YyghException;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserMapper;
import com.atguigu.yygh.user.service.UserService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhmwi
 * @Date 2021/7/16
 * @Dersciption
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserInfo>
        implements UserService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //登录
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //获取参数验空
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        String openid = loginVo.getOpenid();

        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(20001, "数据为空");
        }
        //TODO 校验验证码
        String codeForRedis = redisTemplate.opsForValue().get(phone);
        System.err.println(codeForRedis+"--");
        if (!code.equals(codeForRedis)){
            throw new YyghException(20001,"验证码有误!--");
        }

        //-------------
        //判断是否是微信登陆
        HashMap<String, Object> result = new HashMap<>();
        if (StringUtils.isEmpty(openid)){
            //手机号有值 --> openid为空 --> 正常登陆
            //判断用户是否注册过 根据手机号查询用户
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            UserInfo userInfo = baseMapper.selectOne(queryWrapper);
            if (userInfo == null) {
                //没有用户进行注册
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setName("");
                userInfo.setStatus(1);
                this.save(userInfo);
                //baseMapper.insert(userInfo);
            }
            //有用户完成登录步骤
            //判断用户是否被禁用
            Integer status = userInfo.getStatus();
            if (status == 0) {
                throw new YyghException(20001, "当前用户已被禁用!");
            }

            //将用户名和token返回给前端显示
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }

            String token = JwtHelper.createToken(userInfo.getId(),userInfo.getName());
            result.put("name", name);
            result.put("token", token);
        }else{
            //手机号没值 --> openid不为空 --> 需要绑定手机号
            UserInfo userInfoWx= baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("openid", openid));
            if (userInfoWx == null){
                throw new YyghException(20001,"微信注册有误");
            }
            //给微信绑定手机号
            userInfoWx.setPhone(phone);
            baseMapper.updateById(userInfoWx);
            //判断用户是否被锁定
            if(userInfoWx.getStatus() == 0) {
                throw new YyghException(20001,"用户已经禁用");
            }
            //完成登陆步骤 返回给前端name+token
            String name = userInfoWx.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfoWx.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfoWx.getOpenid();
            }

            result.put("name", name);
            String token = JwtHelper.createToken(userInfoWx.getId(),userInfoWx.getName());
            result.put("token", token);
        }
        return result;
    }

    //添加用户认证
    @Override
    public UserInfo addUserAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = baseMapper.selectById(userId);
        if (userInfo != null){
            //姓名 证件类型 证件编号 证件地址
            userInfo.setName(userAuthVo.getName());
            System.err.println("userAuthVo.getName() -- "+userAuthVo.getName());
            userInfo.setCertificatesType(userAuthVo.getCertificatesType());
            System.err.println("userAuthVo.getCertificatesType() -- "+userAuthVo.getCertificatesType());
            userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
            System.err.println("userAuthVo.getCertificatesNo() -- "+userInfo.getCertificatesNo());
            userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
            System.err.println("userAuthVo.getCertificatesUrl() -- "+userInfo.getCertificatesUrl());
            //进行信息更新
            baseMapper.updateById(userInfo);
        }
        return userInfo;
    }

    //后台 -- 带条件带分页查询用户列表
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        if (userInfoQueryVo != null){
            //条件+分页
            //获取查询条件 封装
            //用户名称
            String name = userInfoQueryVo.getKeyword();
            //用户状态
            Integer status = userInfoQueryVo.getStatus();
            //认证状态
            Integer authStatus = userInfoQueryVo.getAuthStatus();
            //开始时间
            String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
            //结束时间
            String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
            if (!StringUtils.isEmpty(name)){
                queryWrapper.like("name",name);
            }
            if (!StringUtils.isEmpty(status)){
                queryWrapper.eq("status",status);
            }
            if (!StringUtils.isEmpty(status)){
                queryWrapper.eq("status",status);
            }
            if (!StringUtils.isEmpty(authStatus)){
                queryWrapper.eq("auth_status",authStatus);
            }
            if (!StringUtils.isEmpty(createTimeBegin)){
                queryWrapper.ge("create_time",createTimeBegin);
            }
            if (!StringUtils.isEmpty(createTimeEnd)){
                queryWrapper.le("create_time",createTimeEnd);
            }
        }
        //分页
        Page<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, queryWrapper);
        //翻译字段
        userInfoPage.getRecords().stream().forEach(userInfo->{
             this.packUserInfo(userInfo);
        });
        return userInfoPage;
    }

    //锁定解锁用户
    @Override
    public void lock(Long userId, Integer status) {
        if (status.intValue() == 0 || status.intValue() == 1){
            UserInfo userInfo = this.getById(userId);
            System.err.println("原状态: "+userInfo.getStatus());
            userInfo.setStatus(status);
            System.err.println("现状态: "+userInfo.getStatus());
            this.updateById(userInfo);
        }
    }

    //处理认证状态码 处理用户状态 0 1
    private UserInfo packUserInfo(UserInfo userInfo) {
        //处理用户认证状态 未认证 已认证 ...
        String authStatusString = AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus());
        userInfo.getParam().put("authStatusString",authStatusString);
        //处理用户状态0 1
        String statusString = userInfo.getStatus().intValue() == 0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}